﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.ClinicCharts.ChildWindows;
using MedLink2011.Views.ClinicCharts.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.ClinicCharts.ViewModels
{
    public class Evaluation_GastroViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _evaluation_GastroContext;
        private ObservableCollection<Evaluation_Gastro> _evaluation_Gastro;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.ClinicChart> _clinicChartQuery;
        //
       public Evaluation_GastroViewModel()
        {
            if (!IsDesignTime)
            {
                _evaluation_GastroContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadEvaluation_GastroAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current Evaluation_Gastro"
        readonly int loadedClinicChart_Id = MedLink2011.Views.Patients.ViewModels.ClinicChartViewModel.DashLoad_PK;
        //readonly int loadedClinicChart_Id = 1;
        private void LoadEvaluation_GastroAsync()
         {
           if (!_evaluation_GastroContext.IsSubmitting)
            {
                if (loadedClinicChart_Id > 0)
                {
                    PerformAsyncQuery<Evaluation_Gastro>(_evaluation_GastroContext, _evaluation_GastroContext.GetEvaluation_GastrosForClinicChartsQuery(loadedClinicChart_Id), Evaluation_GastroLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<Evaluation_Gastro>(_evaluation_GastroContext, _evaluation_GastroContext.GetEvaluation_GastrosQuery(), Evaluation_GastroLoadedComplete); 
                }
            }
        }

        private EntitySet<Evaluation_Gastro> _evaluation_GastroCollection;
        public EntitySet<Evaluation_Gastro> Evaluation_GastroCollection
        {
            get { return _evaluation_GastroCollection; }
            set
            {
                _evaluation_GastroCollection = value;
                RaisePropertyChanged("Evaluation_GastroCollection");
            }
        }

        private Evaluation_Gastro _currentEvaluation_Gastro;
        public Evaluation_Gastro CurrentEvaluation_Gastro
        {
            get { return _currentEvaluation_Gastro; }
            set
            {
                _currentEvaluation_Gastro = value;
                RaisePropertyChanged("CurrentEvaluation_Gastro");
            }
        }

        #endregion "Load Current Evaluation_Gastro"

        #region Commands

        private void EnableCommands()
        {
            AddNewEvaluation_GastroCommand.IsEnabled = true;
            SaveEvaluation_GastroCommand.IsEnabled = true;
            DeleteEvaluation_GastroCommand.IsEnabled = true;
            PrintEvaluation_GastroCommand.IsEnabled = true;
            SearchEvaluation_GastroCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewEvaluation_GastroCommand = new RelayCommand(AddEvaluation_Gastro);
            SaveEvaluation_GastroCommand = new RelayCommand(SaveEvaluation_Gastro);
            DeleteEvaluation_GastroCommand = new RelayCommand(DeleteEvaluation_Gastro);
            PrintEvaluation_GastroCommand = new RelayCommand(PrintEvaluation_Gastro);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchEvaluation_GastroCommand = new RelayCommand<string>(SearchInEvaluation_Gastro);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentEvaluation_Gastro = (Evaluation_Gastro) _theItem;
            SelectedClinicChart =
                ClinicChartCollection.Where(c => c.ClinicChart_Id == CurrentEvaluation_Gastro.ClinicChart_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.Evaluation_Gastro model = e.DataElement as MedLink2011.Web.Models.Evaluation_Gastro;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Abdomen Wnl : {0} \r\n"+
			"Mass Present Luq : {1} \r\n"+
			"Mass Present Ruq : {2} \r\n"+
			"Mass Present Llq : {3} \r\n"+
			"Mass Present Rlq : {4} \r\n"+
			"Value : {5} \r\n"+
			"Pulsatile : {6} \r\n"+
			"Liver And Spleen Palpitation Wnl : {7} \r\n"+
			"Unable To Palpate Liver : {8} \r\n"+
			"Unable To Palpate Spleen : {9} \r\n"+
			"Enlarged Liver : {10} \r\n"+
			"Enlarged Spleen : {11} \r\n"+
			"Evaluation Gastro Notes : {12} \r\n",

			model.Abdomen_WNL,
			model.Mass_present_LUQ,
			model.Mass_present_RUQ,
			model.Mass_present_LLQ,
			model.Mass_present_RLQ,
			model.Value,
			model.Pulsatile,
			model.Liver_and_spleen_palpitation_WNL,
			model.Unable_To_palpate_Liver,
			model.Unable_To_palpate_Spleen,
			model.Enlarged_Liver,
			model.Enlarged_spleen,
			model.Evaluation_Gastro_Notes
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewEvaluation_GastroCommand
        {
            get;
            private set;
        }
        public RelayCommand SaveEvaluation_GastroCommand
        {
            get;
            private set;
        }
        public RelayCommand DeleteEvaluation_GastroCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintEvaluation_GastroCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchEvaluation_GastroCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInEvaluation_Gastro( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        private void SaveEvaluation_Gastro()
        {
            CurrentEvaluation_Gastro.ClinicChart_Id = SelectedClinicChart.ClinicChart_Id;
            CurrentEvaluation_Gastro.write_date = CurrentTime;
            CurrentEvaluation_Gastro.write_uid = CurrentUser;
            _evaluation_GastroContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("Evaluation_Gastro se ha actualizado");
                    RaisePropertyChanged("Evaluation_GastroCollection");
                    RaisePropertyChanged("CurrentEvaluation_Gastro");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddEvaluation_Gastro()
        {

            MedLink2011.Web.Models.Evaluation_Gastro evaluation_Gastro = new MedLink2011.Web.Models.Evaluation_Gastro();
            Evaluation_GastrosAddCW addNewWindow = new Evaluation_GastrosAddCW();
            addNewWindow.DataContext = evaluation_Gastro;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    evaluation_Gastro.create_date = CurrentTime;
                    evaluation_Gastro.write_date = CurrentTime;
                    evaluation_Gastro.create_uid = CurrentUser;
                    evaluation_Gastro.write_uid = CurrentUser;
                    
                    _evaluation_GastroContext.Evaluation_Gastros.Add(evaluation_Gastro);
                    _evaluation_GastroContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New Evaluation_Gastro has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadEvaluation_GastroAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/ClinicCharts/Pages/PatientsTitlePage?Evaluation_Gastro_id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentEvaluation_Gastro = (Evaluation_Gastro)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"

            
        public EntitySet<ClinicChart> ClinicChartCollection { get; set; }
        private ClinicChart _selectedClinicChart;
        public  ClinicChart SelectedClinicChart
        {
            get { return _selectedClinicChart; }
            set
            {
                _selectedClinicChart = value;
                RaisePropertyChanged("SelectedClinicChart");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //ClinicChart_IdComboBox
            _context = new MedLink2011Context();
            _clinicChartQuery = _context.GetClinicChartsQuery();
            _clinicChartQuery = _clinicChartQuery.OrderBy(e => e.ClinicChart_Id);
            PerformAsyncQuery<ClinicChart>(_context, _clinicChartQuery, ClinicChart_IdComboBoxLoaded);
            ClinicChartCollection = _context.ClinicCharts;
        }
        
        private void ClinicChart_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<ClinicChart> e)
        {
            if (!e.HasError)
            {
                SelectedClinicChart =
                    ClinicChartCollection.Where(c => c.ClinicChart_Id == CurrentEvaluation_Gastro.ClinicChart_Id).SingleOrDefault();
            }
        }


        private void Evaluation_GastroLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<Evaluation_Gastro> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                Evaluation_GastroCollection = _evaluation_GastroContext.Evaluation_Gastros;
                CurrentEvaluation_Gastro = Evaluation_GastroCollection.FirstOrDefault();
                EnableCommands();
            SelectedClinicChart = ClinicChartCollection.Where(c => c.ClinicChart_Id == CurrentEvaluation_Gastro.ClinicChart_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<Evaluation_Gastro> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeleteEvaluation_Gastro()
        {
            _toDelete = true;
            var evaluation_GastroToDelete = CurrentEvaluation_Gastro;
           if (evaluation_GastroToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current Evaluation_Gastro?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _evaluation_GastroContext.Evaluation_Gastros.Remove(evaluation_GastroToDelete);
            _evaluation_GastroContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta evaluation_Gastro no se puede eliminar ya que existen datos que dependen de esta Evaluation_Gastro.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _evaluation_GastroContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  evaluation_Gastro ha sido eliminado exitosamente ... ");
                    //LoadEvaluation_GastroAsync();
                    RaisePropertyChanged("Evaluation_GastroCollection");
                    CurrentEvaluation_Gastro = Evaluation_GastroCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintEvaluation_Gastro()
        {
            if (CurrentEvaluation_Gastro != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "Evaluation_Gastros_" + CurrentEvaluation_Gastro.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.Evaluation_Gastro appt = CurrentEvaluation_Gastro as MedLink2011.Web.Models.Evaluation_Gastro;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new Evaluation_GastrosFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

